package org.jeecg.modules.purchaseList.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.purchaseList.entity.MtPurchase;
import org.jeecg.modules.purchaseList.entity.MtPurchaseEquip;
import org.jeecg.modules.purchaseList.mapper.MtPurchaseEquipMapper;
import org.jeecg.modules.purchaseList.mapper.MtPurchaseMapper;
import org.jeecg.modules.purchaseList.service.IMtPurchaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 采购表单
 * @Author: jeecg-boot
 * @Date:   2023-12-12
 * @Version: V1.0
 */
@Service
public class MtPurchaseServiceImpl extends ServiceImpl<MtPurchaseMapper, MtPurchase> implements IMtPurchaseService {

	@Autowired
	private MtPurchaseMapper mtPurchaseMapper;
	@Autowired
	private MtPurchaseEquipMapper mtPurchaseEquipMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(MtPurchase mtPurchase, List<MtPurchaseEquip> mtPurchaseEquipList) {
		mtPurchaseMapper.insert(mtPurchase);
		MtPurchase mtPurchase1 = mtPurchaseMapper.selectOne(new LambdaQueryWrapper<MtPurchase>().eq(MtPurchase::getReceiptId, mtPurchase.getReceiptId()));
		if(mtPurchaseEquipList!=null && mtPurchaseEquipList.size()>0) {
			for(MtPurchaseEquip entity:mtPurchaseEquipList) {

				//外键设置
				entity.setMtPurchaseId(mtPurchase.getId());
				//先检查数据库中有没有这条数据的id
				if (entity.getId()==null || entity.getId()==""){
					//设置关联的单子id
					entity.setMtPurchaseId(mtPurchase1.getId());
					mtPurchaseEquipMapper.insert(entity);
				}
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(MtPurchase mtPurchase,List<MtPurchaseEquip> mtPurchaseEquipList) {
		mtPurchaseMapper.updateById(mtPurchase);
		//1.先删除子表数据
		mtPurchaseEquipMapper.deleteByMainId(mtPurchase.getId());

		//2.子表数据重新插入
		if(mtPurchaseEquipList!=null && mtPurchaseEquipList.size()>0) {
			for(MtPurchaseEquip entity:mtPurchaseEquipList) {
				//外键设置
				entity.setMtPurchaseId(mtPurchase.getId());
				mtPurchaseEquipMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		mtPurchaseEquipMapper.deleteByMainId(id);
		mtPurchaseMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			mtPurchaseEquipMapper.deleteByMainId(id.toString());
			mtPurchaseMapper.deleteById(id);
		}
	}

}
